package com.example.androidframework.impl

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.example.androidframework.R
import com.example.androidframework.ui.splash.SplashActivity
import com.martin.lib_base.constant.ConstantKey
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.martin.lib_base.ktx.loge
import com.tencent.mmkv.MMKV
import dev.utils.app.ActivityUtils
import dev.utils.app.HandlerUtils
import kotlinx.coroutines.flow.MutableStateFlow

class ActivityLifecycleCallback : Application.ActivityLifecycleCallbacks {
    // 前台页面的数量
    private var foregroundCount = 0

    companion object {
        val isForeground = MutableStateFlow(false)
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        loge("创建Activity === ${activity.javaClass.simpleName}")
        ActivityUtils.getManager().addActivity(activity)
    }

    override fun onActivityStarted(activity: Activity) {
        // 在此处统一做ActionBar返回事件的处理
        activity.findViewById<TitleBar>(R.id.top_bar)?.let {
            it.setLeftClickListener {
                activity.finish()
            }
        }
        foregroundCount++
    }

    override fun onActivityResumed(activity: Activity) {
        loge("ActivityLifecycleCallback : 监听应用回归到前台   ${isForeground.value}  ;  $foregroundCount")
        // 重返应用
        // 已登录
        val isLogin = MMKV.defaultMMKV().decodeBool(ConstantKey.IS_LOGIN, false)
        if (isLogin && activity !is SplashActivity) {
            // 延迟执行
            HandlerUtils.postRunnable({
                 if (activity is LifecycleOwner) {
                     activity.lifecycleScope.launchWhenResumed {

                     }
                 } else {

                 }
            }, 200)
        }
        isForeground.value = foregroundCount > 0
    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {
        foregroundCount--
        isForeground.value = foregroundCount > 0
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        ActivityUtils.getManager().removeActivity(activity)
    }
}